package mr.ali.videoapp.portal.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import mr.ali.videoapp.portal.WeChatConfig;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前页面的链接地址带参数，底层逻辑
 */
@Service
public class WeChatService {

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String URLLINK_URL = "https://api.weixin.qq.com/wxa/generate_urllink";
    private final Map<String, TokenInfo> tokenCache = new ConcurrentHashMap<>();
    private final RestTemplate restTemplate = new RestTemplate();
    @Resource
    private WeChatConfig weChatConfig;
    @Resource
    private ObjectMapper objectMapper;

    public String getAccessToken() throws Exception {
        String key = weChatConfig.getAppid();
        TokenInfo info = tokenCache.get(key);

        if (info != null && System.currentTimeMillis() < info.expireTime) {
            return info.token;
        }

        String url = String.format(TOKEN_URL, weChatConfig.getAppid(), weChatConfig.getSecret());
        try {
            ResponseEntity<Map> res = restTemplate.getForEntity(url, Map.class);
            Map<String, Object> body = res.getBody();
            if (body != null && body.containsKey("access_token")) {
                String token = (String) body.get("access_token");
                int expiresIn = (Integer) body.get("expires_in");

                TokenInfo newInfo = new TokenInfo();
                newInfo.token = token;
                newInfo.expireTime = System.currentTimeMillis() + (expiresIn - 60) * 1000L;

                tokenCache.put(key, newInfo);
                return token;
            } else {
                throw new RuntimeException("获取 token 失败: " + body);
            }
        } catch (Exception e) {
            throw new RuntimeException("调用微信 token 接口失败", e);
        }
    }

    private static class TokenInfo {
        String token;
        long expireTime;
    }
}
